<template>
  <view>
    <view class='profit'>
<!--      <StatusNav :properties="statusNavProperties"/>-->
      <uv-sticky :offsetTop="0"  :customNavHeight="0" bgColor="#fff">
        <view class="heightWrapper">
        <view class="wrapper" :style="{
            background:btnColor()
          }">
          <view class="balance">
            <view class="balance-text">可提现（元）</view>
            <view class="balance-amount" @click="toSettle">{{ accountInfo.balance || 0 }}</view>
          </view>
          <view class="amount-list">
            <view class="amount-item">
              <view class="amount-item-value">+ {{ accountInfo.todayProfit || 0 }}</view>
              <view class="amount-item-text">
                <view style="font-size: 12px">今日</view>
                <view style="font-size: 14px">预估收益</view>
              </view>
            </view>

            <view class="amount-item">
              <view class="amount-item-value">+ {{ accountInfo.monthProfit || 0 }}</view>
              <view class="amount-item-text">
                <view style="font-size: 12px">已进账</view>
                <view style="font-size: 14px">本月收益</view>
              </view>
            </view>

            <view class="amount-item">
              <view class="amount-item-value">{{ accountInfo.total || 0 }}</view>
              <view class="amount-item-text">
                <view style="font-size: 12px">汇总</view>
                <view style="font-size: 14px">累计收益</view>
              </view>
            </view>

            <view class="amount-item">
              <view class="amount-item-value">- {{ accountInfo.withdrawal || 0 }}</view>
              <view class="amount-item-text">
                <view style="font-size: 12px">已到账</view>
                <view style="font-size: 14px">历史提现</view>
              </view>
            </view>
          </view>
          <view class="monthsClass">
            <uv-tabs lineColor="white" :customStyle="{color:'white'}" :current="monthsActive" :list="months" @click="monthsChange">
            </uv-tabs>
          </view>
        </view>

        <view class="search">
          <uv-drop-down
              :extra-active-icon="{name: 'arrow-up', size: '30rpx', color: themConfig.theme.color}"
              :text-active-color="themConfig.theme.color"
              @click="selectMenu"
              ref="dropDown"
              sign="dropDown_1"
          >
            <uv-drop-down-item
                type="1"
                label='订单收益'
                name="none"
                value="">
            </uv-drop-down-item>


            <uv-drop-down-item
                name="order"
                type="2"
                label="筛选"
                value="0">
            </uv-drop-down-item>

          </uv-drop-down>
          <uv-drop-down-popup
              :z-index="10"
              ref="downPopup"
              sign="dropDown_1"
          >
            <template v-slot:default>
              <view style="width: 750rpx;height: auto;background-color: #fff;padding: 20px">

                <view class="sortClass">
                  <view>排序：</view>
                  <view v-for="item in sortList" @click="sortClick(item.value)" :style="{
                      display: 'flex',
                      color: sortActive === item.value? themConfig.theme.color:'#333'
                    }">
                    {{ item.name }}
                    <uv-icon v-if="item.icon" :name="item.icon" :color="sortActive === item.value? themConfig.theme.color:'#333'"
                             size="15"></uv-icon>
                  </view>
                </view>

                <view class="sortClass">
                  <view>收益：</view>
                  <view v-for="item in inComeTypeList" @click="incomeTypeClick(item.value)" :style="{
                      display: 'flex',
                      color: incomeTypeActive === item.value? themConfig.theme.color:'#333'
                    }">
                    {{ item.name }}
                    <uv-icon v-if="item.icon" :name="item.icon" :color="incomeTypeActive === item.value? themConfig.theme.color:'#333'"
                             size="15"></uv-icon>
                  </view>
                </view>

                <view class="sortClass">
                  <view style="width: 35%;" @click="selectDate">
                    <uv-input v-model="date" clearable style="width: 100%;pointer-events: none;" placeholder="日期"
                              border="bottom"></uv-input>
                  </view>
                  <view style="width: 5%"></view>

                </view>

                <view class="sortClass submitBtn">
                  <uv-button @click="searchConfirm" type="primary" style="margin-right: 20px" :color="themConfig.theme.color"
                             size="small" plain text="确定"></uv-button>
                  <uv-button @click="searchRest" type="error" size="small" plain text="清空"></uv-button>
                </view>
              </view>
            </template>
          </uv-drop-down-popup>
        </view>

        <view class="order-total">
          <view>
            <uv-input @blur="searchConfirm" @confirm="searchConfirm" v-model="searchParams.orderNo" clearable style="width: 100%" placeholder="输入单号搜索"
                      border="bottom"></uv-input>
          </view>
          <view>
            数量：{{ dataPage.total }}
            &nbsp;
            金额：{{ dataPage.ext||dataPage.total }}
          </view>
        </view>
      </view>
      </uv-sticky>
      <PageBody :properties="pageBody" >
        <template v-slot:body>
          <view class="order-list-wrapper">
            <view class="order-list" v-if="userOrderProfitRecord.length">
              <view class="ordercard" v-for="order in userOrderProfitRecord">
                <view class="order-top">
                  <view style="display: flex">
                    <text>{{ order.orderName }}</text>
                    <text style="margin-left: 5px">{{ order.orderNo }}</text>
                    <uv-icon @click="copyOrderNo(order.orderNo)" name="file-text"></uv-icon>
                  </view>
                  <view @click="goOrderDetail(order.orderId)">
                    <text>收益：</text>
                    <text :style="{
                      color: themConfig.theme.color,
                      fontSize:'16px'
                    }">+{{ order.amount }}
                    </text>
                  </view>
                </view>

                <uv-gap @click="goOrderDetail(order.orderId)" height="15" bgColor=""></uv-gap>

                <view @click="goOrderDetail(order.orderId)" class="order-bottom">
                  <view class="time-text">
                    <text>时间：</text>
                    <text>{{ order.orderTime }}</text>
                  </view>
                  <view>
                    <Dict :properties="{dictType:'income_type',dictValue:order.incomeType,size:'mini'}"/>
                  </view>
                  <view>
                    <Dict :properties="{dictType:'settlement_state',dictValue:order.state,size:'mini'}"/>
                  </view>
                </view>

              </view>
            </view>

            <view v-else>
              <Empty :show="true"/>
            </view>

            <uv-load-more v-if="isReachBottom" @loadmore="loadmore"
                          :status="loading.status"
                          :loading-text="loading.loadingText"
                          :loadmore-text="loading.loadmoreText"
                          nomore-text=" "/>

            <uv-gap height="2" bgColor=""></uv-gap>
          </view>

        </template>
      </PageBody>
    </view>
    <uv-calendars :color="themConfig.theme.color" ref="calendar" mode="single" @confirm="confirmDate"></uv-calendars>
    <FloatingBackHome/>
  </view>
</template>
<script>
import StatusNav from '@/components/school/statusNav';
import PageBody from '@/components/school/pageBody';
import {mapGetters} from "vuex";
import {toLogin} from '@/libs/login.js';
import diyJson from '@/config/diy.js';
import * as MemberApi from '@/api/member/user.js'
import Dict from '@/components/school/dict';

const app = getApp();

export default {
  computed: mapGetters(['isLogin', 'userInfo', 'schoolId']),
  components: {
    StatusNav,
    PageBody,
    Dict,
  },

  data() {
    return {
      monthsActive: '',
      months: [
        {
          name: '所有',
          value: ''
        },
        {
          name: '12月',
          value: '12'
        }, {
          name: '1月',
          value: '01'
        },
        {
          name: '2月',
          value: '02'
        },
        {
          name: '3月',
          value: '03'
        },
        {
          name: '4月',
          value: '04'
        },
        {
          name: '5月',
          value: '05'
        },
        {
          name: '6月',
          value: '06'
        },
        {
          name: '7月',
          value: '07'
        }, {
          name: '8月',
          value: '08'
        },
        {
          name: '9月',
          value: '09'
        },
        {
          name: '10月',
          value: '10'
        },
        {
          name: '11月',
          value: '11'
        }
      ],
      // 表示value等于这些值，就属于默认值
      defaultValue: [''],
      // 筛选结果
      result: [{name: 'order', label: '最新发布', value: 'new'}],
      // { name: 'order', label: '最新发布', value: 'new' }
      activeName: 'order',

      sortActive: 'time',
      incomeTypeActive: '',
      sortList: [
        // {
        //   "name": "综合",
        //   "value": 'all'
        // },
        {
          "name": "时间倒序",
          "value": 'time',
          "icon": 'arrow-downward'
        },
        {
          "name": "金额倒序",
          "value": 'amount',
          "icon": 'arrow-downward'
        }
      ],
      inComeTypeList: [],
      date: '',
      order: {
        label: '综合排序',
        value: 'all',
        activeIndex: 0,
        color: '#333',
        activeColor: '#2878ff',
        child: [{
          label: '综合排序',
          value: 'all'
        }, {
          label: '最新发布',
          value: 'new'
        }, {
          label: '低价优先',
          value: 'money'
        }]
      },

      themConfig: diyJson.commonStyle,
      accountInfo: {
        todayProfit: 0.00,
        monthProfit: 0.00,
        "total": 0.00,
        "balance": 0.00,
        "withdrawal": 0.00
      },

      loading: {
        status: 'nomore',
        loadingText: '加载中',
        loadmoreText: '点击加载更多',
      },

      userOrderProfitRecord: [],
      dataPage: {
        current: 1,
        pages: 1,
        total: 0,
      },

      searchParams: {},
      isReachBottom: false,
      pageBody: {

      },

      statusNavProperties: { // 筛选条件
        title: "我的收益",
        setStyle: {
          bgColor: 'white',
          enableBack: true,
          titleStyle: {}
        }
      },

    };
  },
  onPullDownRefresh() {
    this.getAccountInfo();
    this.getUserOrderProfitRecord();
    uni.stopPullDownRefresh();
  },
  onLoad: function (options) {
    if (!this.isLogin) {
      toLogin();
    }
  },
  onShow() {
    this.initParams();
    this.getAccountInfo();
    this.getUserOrderProfitRecord();
  },
  mounted() {
    this.computeAmountHeight();
  },

  methods: {

    async computeAmountHeight() {
      const query = uni.createSelectorQuery().in(this);
      let that = this;
      query.select('.heightWrapper')
      .boundingClientRect((dome) => {
        // console.log("height", dome.height)
        // that.pageBody['paddingTop'] = dome.height;
      })
      .exec();
    },

    initParams() {
      let date = new Date();
      let moth = date.getMonth() + 1;
      console.log("date.getMonth()", date.getMonth())
      let monthStr;
      if (moth < 10) {
        monthStr = '0' + (moth);
      } else {
        monthStr = '' + (moth);
      }

      for (let i = 0; i < this.months.length; i++) {
        if (this.months[i].value === monthStr) {
          this.monthsActive = i;
          break;
        }
      }

      this.searchParams['orderBy'] = 'user_settlement_info.create_time desc';
      this.searchParams['month'] = date.getFullYear() + '-' + monthStr;
    },

    // 切换月份
    monthsChange(e) {
      console.log("months", e);
      if (e.value) {
        let year = new Date().getFullYear();
        let month = year + '-' + e.value;
        this.searchParams['month'] = month;
      } else {
        delete this.searchParams['month'];
      }
      this.getUserOrderProfitRecord();
    },

    // 点击提现金额
    toSettle() {
      uni.navigateTo({
        url: '/pages/users/user_cash/index'
      })
    },

    initIncomeType() {
      let arr = [{name: '所有', value: ''}]
      let data = this.$store.state.app.dicData;
      if (data != null) {
        if (typeof data === 'string') {
          data = JSON.parse(data)
        }
        let dictDataV = data['income_type'];
        for (const dictDataVKey in dictDataV) {
          let d = dictDataV[dictDataVKey];
          arr.push({'name': d.text, 'value': d.value})
        }
        this.inComeTypeList = arr;
      }
    },

    onPageScroll() {
      // 滚动后及时更新位置
      this.$refs.dropDown.init();
    },

    // 选择筛选菜单
    selectMenu(e) {
      console.log("name", e);
    },

    // 弹出日期
    selectDate() {
      this.$refs.calendar.open();
    },

    // 选择日期
    confirmDate(e) {
      console.log('日历选择：', e);
      this.date = e.fulldate;
      this.searchParams['date'] = e.fulldate;
    },

    // 点击搜索
    searchConfirm() {
      this.loading.status = 'nomore';

      if (this.searchParams.orderNo || this.searchParams['date']) {
        delete this.searchParams['month'];
        this.monthsActive = 0;
      }
      console.log("searchParams", this.searchParams);
      this.$refs.downPopup.clickOverlay();
      this.getUserOrderProfitRecord();
    },

    // 清空搜索条件
    searchRest() {
      this.loading.status = 'nomore';
      delete this.searchParams['date'];
      delete this.searchParams['orderNo'];
      this.searchParams['orderBy'] = 'user_settlement_info.create_time desc'
      delete this.searchParams['incomeType'];
      this.date = null;
      this.sortActive = 'time';
      this.incomeTypeActive = '';
    },

    // 点击排序
    sortClick(val) {
      this.sortActive = val;
      if (val === 'all') {
        delete this.searchParams['orderBy'];
      } else if (val === 'time') {
        this.searchParams['orderBy'] = 'user_settlement_info.create_time desc'
      } else {
        this.searchParams['orderBy'] = 'user_settlement_info.amount desc'
      }
      // this.getUserOrderProfitRecord();
    },

    // 点击接单人收益
    incomeTypeClick(value) {
      this.incomeTypeActive = value;
      if (!value) {
        delete this.searchParams['incomeType'];
      } else {
        this.searchParams['incomeType'] = value;
      }
    },

    copyOrderNo(orderNo) {
      uni.setClipboardData({
        data: orderNo,
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'success',
            duration: 2000
          });
        }
      });
    },

    // 获取账户金额
    getAccountInfo() {
      MemberApi.accountInfo().then((res) => {
        this.accountInfo = res.data;
      })
    },

    getUserOrderProfitRecord() {
      this.userOrderProfitRecord = []
      MemberApi.getUserOrderProfitRecord({...this.searchParams, schoolId: this.schoolId}).then((res) => {
        this.userOrderProfitRecord = res.data.records;
        this.reqApiResHandler(res);
        this.initIncomeType();
      })
    },

    // 公共请求响应结果处理
    reqApiResHandler(res) {
      this.dataPage.current = res.data.current;
      this.dataPage.pages = res.data.pages;
      this.dataPage.total = res.data.total;
      this.dataPage.ext = res.data.ext;
    },
    // 滚到底部
    scrolltolower() {
      this.isReachBottom = true;
      this.loading.status = 'nomore';
      if (this.dataPage.current < this.dataPage.pages) {
        this.loading.status = 'loadmore';
      }
    },
    loadmore() {
      if (this.dataPage.current < this.dataPage.pages) {
        this.loading.status = 'loading';
        MemberApi.getUserOrderProfitRecord({...this.searchParams, schoolId: this.schoolId, current: this.dataPage.current + 1}).then(
            res => {
              res.data.records.forEach(item => {
                this.userOrderProfitRecord.push(item)
              })
              this.reqApiResHandler(res);
              this.loading.status = 'loadmore';
            })
      }
    },

    goBack(url) {
      // #ifdef H5
      return history.back();
      // #endif
      // #ifndef H5
      return uni.navigateBack({
        delta: 1,
      })
      // #endif
    },

    btnColor() {
      return 'linear-gradient(to top,' + this.themConfig.theme.subColor + ',' + this.themConfig.theme.color + ')'
      // return' linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))';
    },

    goOrderDetail(orderId) {
      if (!this.custom) {
        this.$store.commit('SET_URL_PARAMS', {orderId: orderId});
        uni.navigateTo({
          url: '/pages/school/order-detail/index'
        });
      }
    },

    getApp() {
      return app;
    },

  },
  onReachBottom() {
    this.scrolltolower();
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  padding: 40rpx;
  color: white;
  padding-bottom: 10rpx;
}
.heightWrapper{
  //position: fixed;
}
.balance {
  text-align: center;
  margin-bottom: 20px;

  .balance-amount {
    font-size: 50px;
  }

  .balance-text {
    margin: 10px 0;
    font-size: 20px;
  }
}

.amount-list {
  display: flex;
  justify-content: space-between;

  .amount-item {
    text-align: center;
  }

  .amount-item-value {
    font-size: 23px;
    margin-bottom: 10px;
  }

  .amount-item-text {
    font-size: 17px;
  }
}

.search {
  background-color: white;

  .sortClass {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .sortClass:nth-child(2) {
    margin: 40rpx 0;
  }
}

.ordercard {
  background-color: white;
  padding: 20rpx;
  margin: 0rpx 0 20rpx 0rpx;
  border-radius: 10px;
}

.order-top {
  display: flex;
  justify-content: space-between;
}

.order-list {
  padding: 0rpx 20rpx 0 20rpx;
}

.order-total {
  display: flex;
  justify-content: space-between;
  padding: 0rpx 20rpx;
  align-items: center;
}

.order-bottom {
  display: flex;
  justify-content: space-between;
}

.submitBtn {
  justify-content: right !important;
  margin-top: 20rpx;
}

.time-text {
  font-size: 12px;
  color: #606266;
}

.monthsClass {
  position: relative;
  margin-top: 20rpx;

  ::v-deep .uv-tabs__wrapper__nav__item__text {
    color: white !important;
  }
}
</style>
